package cn.shop.admin.controller;

import cn.shop.admin.entity.mainSiteAnnouncementModule.MainSiteGames;
import cn.shop.admin.req.MainSiteGamesQueryReq;
import cn.shop.admin.service.MainSiteGamesService;
import cn.shop.base.MyPage;
import cn.shop.thiredparty.config.OSSConfig;
import cn.shop.thiredparty.entity.Metadata;
import cn.shop.thiredparty.service.AliOssService;
import cn.shop.utils.ApiResult;
import cn.shop.utils.Putif;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 主站合作游戏
 *
 * @author : 李一涵
 * @since : 2022-10-8 11:46
 */
@RestController
@RequestMapping("/api/v1/mainSiteGames")
public class MainSiteGamesController {

    @Resource
    private MainSiteGamesService gamesService;
    @Resource
    private AliOssService ossService;
    @Resource
    private OSSConfig config;

    /**
     * 新增主站合作游戏
     *
     * @param games 合作游戏
     * @return 返回结果
     */
    @PostMapping("/insert")
    public ApiResult<Map<String, Object>> save(@Validated @RequestBody MainSiteGames games) {
        return ApiResult.result(gamesService.save(games));
    }

    /**
     * 获取主站合作游戏列表
     *
     * @param type 类型
     * @return 返回结果
     */
    @GetMapping("/list")
    public ApiResult<List<Map<String, Object>>> list(Integer type) {
        List<MainSiteGames> list = gamesService.lambdaQuery()
                .eq(type != null, MainSiteGames::getType, type)
                .orderByDesc(MainSiteGames::getUpdateTime)
                .list();
        List<Map<String, Object>> data = list.stream().map(this::format).collect(Collectors.toList());
        return ApiResult.success(data);
    }

    /**
     * 删除主站合作游戏
     *
     * @param id 编号
     * @return 返回结果
     */
    @DeleteMapping("/delete/{id}")
    public ApiResult<Map<String, Object>> delete(@PathVariable long id) {
        MainSiteGames delete = new MainSiteGames();
        delete.setId(id);
        return ApiResult.result(gamesService.removeById(delete));
    }

    /**
     * 上传图片接口
     *
     * @param file 要上传的图片
     * @return 返回结果
     */
    @PostMapping("/upload")
    public ApiResult<Map<String, Object>> upload(@RequestParam MultipartFile file){
        //不是图片的处理
        if(!isImage(file.getOriginalFilename())){
            return ApiResult.fail("文件不是图片");
        }
        //图片大小不超过5MB
        if(file.getSize() / 1024 / 1024 >= 5){
            return ApiResult.fail("图片大小不能超过5M");
        }
        Metadata metadata = new Metadata();
        metadata.setFilename(file.getOriginalFilename());
        metadata.setContentType(file.getContentType());
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String filename = ossService.upload(metadata, inputStream);
        return ApiResult.success(Putif.start()
                        .anyway("filename", filename)
                        .anyway("fileUrl", config.getPrefix() + "/" + filename).get());
    }

    private boolean isImage(String originalFilename) {
        if (originalFilename == null) {
            return false;
        }
        if(originalFilename.contains(".")){
            String fileExt = originalFilename.substring(originalFilename.lastIndexOf("."));
            fileExt = fileExt.toLowerCase();
            return fileExt.equals(".jpg")
                    || fileExt.equals(".jpeg")
                    || fileExt.equals(".gif")
                    || fileExt.equals(".png")
                    || fileExt.equals(".bmp");
        }
        return false;
    }

    private Map<String, Object> format(MainSiteGames game) {
        return Putif.start()
                .anyway("id", game.getId())
                .anyway("url", game.getUrl())
                .anyway("picture", config.getPrefix() + game.getPicture())
                .anyway("title", game.getTitle())
                .get();
    }
}
